<template>
  <div ref="pageComBox" class="NewCustomer page_wrapper">
    <div ref="otherBox">
      <Params ref="params" public-pool remark-count @search="onSearch" />
      <div class="static_tips" v-if="staticInfo && staticInfo.length">
        <span>您有</span>
        <div class="" v-for="(item, index) in staticInfo" :key="index">
          <span class="underline" @click="setParams(item)">{{
            item.time
          }}</span>
          <span>天以上未跟进客户</span>
          <span>{{ item.num }}人，</span>
        </div>
      </div>
      <el-row type="flex" justify="space-between" class="mb-3">
        <el-col :xs="12">
          <el-button-group>
            <el-button
              type="primary"
              size="small"
              :disabled="assistDisabled"
              @click="joininPublicPool"
              >加入公共池</el-button
            >
            <el-button
              type="primary"
              size="small"
              :disabled="assistDisabled"
              @click="allotEvent"
              >分配</el-button
            >
            <el-button type="primary" size="small" @click="downPackage"
              >导出MD5排重包</el-button
            >
          </el-button-group>
          <el-radio-group
            class="el_radio_group"
            v-model="isNew"
            @input="onFilterChange"
          >
            <el-radio label="">全部</el-radio>
            <el-radio label="1">新客户</el-radio>
            <el-radio label="2">再分配客户</el-radio>
            <el-radio label="3">历史客户</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
    </div>

    <el-table
      :data="dataList"
      ref="multipleTable"
      style="width: 100%"
      :row-class-name="$getTableClass"
      @selection-change="handleSelectionChange"
      @select="select"
      @select-all="selectAll"
      v-loading="loading"
      element-loading-text="加载中..."
      @sort-change="sortChange"
      :max-height="tableHeight"
      :key="tableHeight"
      v-tabscroll="$getTableHeight"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="客户信息" width="140">
        <template slot-scope="{ row }">
          <tab-user :user="row" :list="dataList" v-if="row"></tab-user>
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" :width="sortTdWidth">
      </el-table-column>
      <el-table-column prop="media" label="媒体" :width="sortTdWidth">
      </el-table-column>
      <el-table-column label="状态" :width="sortTdWidth">
        <template slot-scope="{ row }">
          {{ showFollowProcess(row.progress) }}
        </template>
      </el-table-column>
      <el-table-column label="锁定状态" :width="80">
        <template slot-scope="{ row }">
          <el-tag
            type="danger"
            class="tab_el_tag"
            size="mini"
            v-if="row.lock == 1"
            >锁定</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="employee.name" label="持有人" :width="80">
      </el-table-column>
      <!-- <el-table-column label="通话状态" :width="80">
        <template slot-scope="{row}">
          {{PASSOPTIONSSTATUSLIST[row.call]}}
        </template>
      </el-table-column> -->
      <el-table-column label="客户标签" :width="80">
        <template slot-scope="{ row }">
          <el-tag
            v-for="(item, index) in getTagList(row.label)"
            class="tab_el_tag"
            size="mini"
            :key="index"
            >{{ item }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="公共池" :width="80">
        <template slot-scope="{ row }">
          <public-poll :id="row.publicPool" />
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="条件备注" :width="tdWidth">
        <template slot-scope="{ row }">
          <condition-remark :list="getTagList(row.remark, ';')" />
        </template>
      </el-table-column>
      <el-table-column label="跟进记录" :width="longTdWidth">
        <template slot-scope="scope">
          <el-popover placement="left-end" trigger="hover" width="500">
            <div class="remarkBox">
              <div class="remarkList">
                <div
                  class="item mb-3"
                  v-for="(item, index) in scope.row.remarkList"
                  :key="index"
                >
                  <div class="remark">{{ item.remark }}</div>
                  <div class="createBy pl-3">{{ item.createBy }}</div>
                  <div class="updateDate ml-3">{{ item.updateDate }}</div>
                </div>
              </div>
            </div>
            <div class="remarkList" slot="reference">
              <div
                class="item"
                :class="{ hide: index > 2 }"
                v-for="(item, index) in scope.row.remarkList"
                :key="index"
              >
                <div class="remark">{{ cutWordLength(item.remark,'17') }}</div>
                <div class="createBy pl-3">{{ item.createBy }}</div>
                <div class="updateDate ml-3">{{ item.updateDate }}</div>
              </div>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="未跟进时间" :width="100">
        <template slot-scope="scope">
          <div class="red">{{ scope.row.days }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="remarkDate"
        label="最后备注日期"
        sortable="remark_date"
        :width="tdWidth"
      />
      <el-table-column
        prop="createDate"
        label="入库时间"
        sortable="create_date"
        :width="tdWidth"
      />
      <el-table-column
        prop="distributeDate"
        label="分配时间"
        sortable="distribute_date"
        :width="tdWidth"
      />
      <el-table-column label="操作" width="170" align="center" fixed="right">
        <template slot-scope="{ row }">
          <div class="d-flex">
            <el-button type="primary" @click="assistHandle(row.id)" size="small"
              >点评</el-button
            >
            <el-button
              type="primary"
              @click="getRecordList(row.mobile)"
              size="small"
              >查看录音</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <BasePagination
      v-model="page"
      :total="totalCount"
      :pageSize="pageSize"
      @change="pageOnChange"
    />
    <el-dialog
      title="点评"
      width="30%"
      :visible.sync="chooseDialogVisi"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form">
        <el-form-item>
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="content"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="chooseDialogVisi = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="assistSubmitLoading"
          @click="assistSubmit"
          >提交</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="录音列表"
      width="1000px"
      :visible.sync="dialog.visible"
      :close-on-click-modal="false"
    >
      <el-table :data="dialog.list">
        <el-table-column
          property="employeeName"
          label="员工名称"
          width="100"
        ></el-table-column>
        <el-table-column
          property="employeePhone"
          label="员工手机号码"
          width="150"
        ></el-table-column>
        <el-table-column property="fileUrl" label="录音文件"></el-table-column>
        <el-table-column property="name" label="操作" width="360">
          <template slot-scope="{ row }">
            <div class="d-flex">
              <audio
                class="audio mr-2"
                :src="row.fileUrl"
                loop=""
                controlsList="nodownload"
                mutex
                controls
              ></audio>
              <el-button @click="download(row.fileUrl, name)" type="text"
                >下载</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 跟进弹框 开始 -->
    <glsx-dialog
      title="跟进"
      width="60%"
      :show="showDialog"
      @close="closeDialog()"
    >
      <follow-up
        ref="followUpCom"
        v-if="showDialog"
        :data="selectItem"
        @change="onChange"
      ></follow-up>
      <div slot="footer">
        <el-button
          type="primary"
          size="small"
          :loading="updateLoading"
          @click="updateCustomer()"
          >保存</el-button
        >
        <el-button type="default" size="small" @click="closeDialog()"
          >取消</el-button
        >
      </div>
    </glsx-dialog>
    <!-- 跟进弹框 end -->

    <!-- 分配弹框 开始 -->
    <glsx-dialog
      :show="allotDialog"
      title="分配"
      width="30%"
      @close="closeAllotDialog()"
    >
      <el-form ref="addForm" :model="addForm" label-width="100px">
        <el-form-item label="门店">
          <el-select
            v-model="addForm.shopId"
            @change="shopSelectChange"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in shopOptionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="团队">
          <el-select
            v-model="addForm.teamId"
            @change="teamSelectChange"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in teamOptionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工">
          <el-select
            v-model="addForm.employeeId"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in employeeOptionList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button
          type="primary"
          size="small"
          :loading="assistSubmitLoading"
          @click="saveAllotInfo()"
          >保存</el-button
        >
        <el-button type="default" size="small" @click="closeAllotDialog()"
          >取消</el-button
        >
      </div>
    </glsx-dialog>
    <!-- 分配弹框 end -->

    <!-- 导出排重包 -->
    <DownloadPopup v-model="showDownPopup" v-if="showDownPopup" />
  </div>
</template>

<script>
//import Params from "./Params.vue";
import Params from "@/components/common/params.vue";
import {
  allCustomerPage,
  customerComment,
  addPool,
  getRecordList,
  shopList,
  allTeamList,
  getEmployee,
  customerDistribute,
} from "@/api/customer";
import { followUpOptions, startOptions, passOptions } from "./config";
import { mapState } from "vuex";
import FollowUp from "@/components/follow";
import { SEXTYPELIST, PASSOPTIONSSTATUSLIST } from "@/common/constants";
import TabUser from "@/components/user";
import { showFollowProcess, getTagList, received } from "@/utils/util";
import {
  GET_CUSTOMER_STATISTICS_COMPLETE,
  GET_TEAM_ALL_CUSTOMER,
  GET_ALL_COMPLETE_CUSTOMER
} from "@/http/customer";
import DownloadPopup from "@/components/download/index.vue";
import moment from "moment";
export default {
  components: { Params, FollowUp, TabUser, DownloadPopup },
  data() {
    return {
      fieldList: [],
      page: 1,
      pageSize: 100,
      dataList: [],
      totalCount: 0,
      form: {},
      followUpOptions,
      startOptions,
      passOptions,
      assistDisabled: true,
      chooseDialogVisi: false,
      assistSubmitLoading: false,
      content: "",
      userSelectArr: [],
      dialog: {
        visible: false,
        list: [],
      },
      audiolist: [],
      customerId: "",
      sortTdWidth: 56,
      smallWidth: 110,
      tdWidth: 160,
      longTdWidth: 500,
      showDialog: false,
      selectItem: {},
      SEXTYPELIST,
      PASSOPTIONSSTATUSLIST,
      showFollowProcess: (str) => showFollowProcess(str),
      getTagList: (str, id) => getTagList(str, id),
      updateLoading: false,
      allotDialog: false,
      shopOptionList: [],
      teamOptionList: [],
      employeeOptionList: [],
      addForm: {},
      loading: false,
      staticInfo: [],
      showDownPopup: false,
      isNew: "",
      tableHeight:0
    };
  },
  mounted() {
    this.fieldList = JSON.parse(JSON.stringify(this.fieldList1));
    received("update.success", this.allCustomerPage);
    this.getShopList();
    this.getStatic();
    // 计算表格的高度
    let _this = this
    this.$getTableHeight();
    window.onresize = function () {
      _this.$getTableHeight();
    };
  },
  computed: {
    ...mapState({
      fieldList1: (state) => state.myClient.fieldList,
    }),
  },
  watch: {
    fieldList1(val) {
      this.fieldList = JSON.parse(JSON.stringify(val));
    },
    "dialog.visible": {
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.listenVideo();
          });
        }
      },
      deep: true,
    },
  },
  methods: {
    async download(url, name) {
      this.downloadFile(url);
    },
    downloadFile(url) {
      const DownloadLink = document.createElement("a");
      DownloadLink.href = url;
      document.body.appendChild(DownloadLink);
      DownloadLink.click(); // 触发a标签的click事件
      DownloadLink.style = "display: none"; // 创建一个隐藏的a标签
    },

    async getRecordList(mobile) {
      const res = await getRecordList(mobile);
      if (!res.result) return;

      if (!res.data.length) {
        this.$message.error("暂无数据");
        return;
      }

      this.dialog.list = res.data;
      this.dialog.visible = true;
    },
    listenVideo() {
      this.audiolist = document.querySelectorAll("audio");
      this.audiolist.forEach((item) => {
        item.addEventListener("play", (e) => {
          this.pauseAll(e.target);
        });
      });
    },
    pauseAll(target) {
      this.audiolist.forEach((item) => {
        target !== item && item.pause();
      });
    },
    async allCustomerPage(form) {
      this.showAppLoading();
      try {
        this.loading = true;
        await GET_ALL_COMPLETE_CUSTOMER({
          page: this.page,
          size: this.pageSize,
          paramObject: { ...form },
        }).then((res) => {
          this.loading = false;
          const { data } = res;
          this.dataList = data.dataList || [];
          this.totalCount = data.totalCount;
          this.$nextTick(() => {
            let index = 0;
            const list = document.querySelectorAll("tr");
            const tbody = document.querySelector("tbody");
            const comment = tbody.getElementsByClassName("comment");
            if (!comment) {
              return false;
            }
            for (let index1 = comment.length - 1; index1 >= 0; index1--) {
              const element = comment[index1];
              element.remove();
            }
            list.forEach((dom) => {
              if (dom.classList.contains("el-table__row")) {
                if (this.dataList[index] && this.dataList[index].comment) {
                  const div = document.createElement("div");
                  div.innerHTML = `主管点评：${this.dataList[index].comment}`;
                  div.classList.add("comment");
                  dom.parentNode.insertBefore(div, dom);
                }
                index++;
              }
            });
          });
        });
        this.hideAppLoading();
      } catch (error) {
        this.hideAppLoading();
      }
    },
    pageOnChange(row) {
      console.log(row);
      this.page = row.page;
      if (row.pageSize) {
        this.pageSize = row.pageSize;
      }
      this.$refs.params.search();
    },

    handleSelectionChange(e) {
      this.assistDisabled = e.length === 0;
      this.idArr = e.map((element) => element.id);
    },
    select(selection, row) {
      // if (selection.length > 1) {
      //   const del_row = selection.shift()
      //   this.$refs.multipleTable.toggleRowSelection(del_row, false)
      // }
    },
    selectAll(selection) {
      // if (selection.length > 1) {
      //   selection.length = 1
      // }
    },
    async assistHandle(id) {
      console.log("id", id);
      this.customerId = id;
      this.chooseDialogVisi = true;
    },
    async assistSubmit() {
      this.assistSubmitLoading = true;
      try {
        const form = {
          // customerId: this.idArr[0],
          customerId: this.customerId,
          content: this.content,
        };
        await customerComment(form).then((res) => {
          this.$message.success(res.message);
          this.content = "";
          this.chooseDialogVisi = false;
          this.$refs.params.search();
        });
        this.assistSubmitLoading = false;
      } catch (error) {
        this.assistSubmitLoading = false;
      }
    },
    joininPublicPool() {
      this.$confirm(`确认加入公共池?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = "请求中...";
            try {
              // await addPool({ id: this.idArr[0] }).then(res => {
              await addPool({ idList: this.idArr }).then((res) => {
                this.$message({
                  message: res.message,
                  type: "success",
                });
              });
              done();
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "确定";
              this.$refs.params.search();
            } catch (error) {
              done();
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "确定";
            }
          } else {
            done();
          }
        },
      });
    },

    // 保存跟进数据
    updateCustomer() {
      this.updateLoading = true;
      this.$refs.followUpCom.saveInfo();
    },

    // 关闭弹框
    closeDialog() {
      this.showDialog = false;
      this.customerPublicPage();
    },

    // 监听组件变化
    onChange(e) {
      this.updateLoading = false;
      if (e) {
        this.closeDialog();
      }
    },

    // 打开跟进弹框
    followUpHandle(item) {
      this.selectItem = Object.assign({}, item);
      this.showDialog = true;
    },

    // 展示条件备注
    showRemark(str) {
      if (!str) {
        return [];
      }
      let m = str.split(";");
      return m;
    },

    // 打开分配弹框
    allotEvent() {
      this.allotDialog = true;
    },

    // 关闭分配弹框
    closeAllotDialog() {
      this.allotDialog = false;
      this.addForm = {};
    },

    // 获取门店列表
    getShopList() {
      shopList({ type: 1 }).then((res) => {
        this.shopOptionList = res.data;
      });
    },

    // 获取团队列表
    async shopSelectChange() {
      let o = this.addForm;
      if (o.teamId) {
        delete o.teamId;
      }
      if (o.employeeId) {
        delete o.employeeId;
      }
      await allTeamList({ shopId: o.shopId, type: 1 }).then((res) => {
        this.teamOptionList = res.data;
      });
    },

    // 获取员工列表
    async teamSelectChange() {
      let o = this.addForm;
      if (o.employeeId) {
        delete o.employeeId;
      }
      await getEmployee({
        shopId: o.shopId,
        teamId: o.teamId,
        type: 1,
      }).then((res) => {
        this.employeeOptionList = res.data || [];
      });
      this.employeeSelectLoading = false;
    },

    // 分配客户
    saveAllotInfo() {
      this.assistSubmitLoading = true;
      let oParams = JSON.parse(JSON.stringify(this.addForm));
      oParams.idList = this.idArr;
      customerDistribute(oParams).then((res) => {
        this.assistSubmitLoading = false;
        if (res.code === 200) {
          this.$message.success(res.message);
          this.$refs.params.search();
          this.closeAllotDialog();
        }
      });
    },

    // 获取未跟进客户统计
    getStatic() {
      let form = this.$refs.params.form || {};
      let params = { ...form};
      GET_CUSTOMER_STATISTICS_COMPLETE(params).then((res) => {
        let obj = res.data || {};
        let arr = [];
        for (let k in obj) {
          console.log(k);
          arr.push({ time: k, num: obj[k] });
        }
        this.staticInfo = arr || [];
      });
    },

    // 设置参数
    setParams(row) {
      this.$refs.params.setParams("followDayCount", row.time);
      this.$refs.params.search();
    },

    // 导出MD5 重排包
    downPackage() {
      this.showDownPopup = true;
    },

    // 监听表格排序
    sortChange({ column, prop, order }) {
      console.log(column);
      //this.formInline.orderField = prop;
      let str = `${column.sortable} asc`;
      if (order == "ascending") {
        str = `${column.sortable} asc`;
      } else {
        str = `${column.sortable} desc`;
      }
      this.$refs.params.setParams("sort", str);
      this.$refs.params.search();
      //this.getList();
    },

    // 是否新用户
    isNewUser(row) {
      let _name = "";
      let isTrue = moment().isSame(row.createDate, "day");
      if (isTrue) {
        _name = "current_user";
      }
      return _name;
    },

    // 筛选客户
    onFilterChange(e) {
      this.$refs.params.setParams("isNew", e);
      this.$refs.params.search();
    },

    // 搜索
    onSearch(form){
      this.allCustomerPage(form)
      this.getStatic()
    }

  },
};
</script>

<style lang="scss">
.NewCustomer {
  padding: 20px;
}

.txt {
  padding: 8px 0;
}

.wrapping {
  margin-right: 10px;
  margin-bottom: 10px;
}

.btn {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}

.current_user {
  .name {
    span {
      color: #f00;
    }
  }
}

.el_radio_group {
  margin-left: 10px;
}
</style>
